<template>
  <div class="stock-list">
    <!-- 页面级Loading -->
    <div v-if="pageLoading" class="page-loading">
      <div
        v-loading="true"
        element-loading-text="正在加载股票列表..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        class="loading-overlay"
      >
        <div style="height: 100vh"></div>
      </div>
    </div>

    <!-- 错误信息显示 -->
    <div v-else-if="pageError" class="page-error">
      <el-result icon="error" :title="errorTitle" :sub-title="errorMessage">
        <template #extra>
          <el-button type="primary" @click="retryLoad">重新加载</el-button>
        </template>
      </el-result>
    </div>

    <!-- 正常内容 -->
    <div v-else>
      <div class="page-header">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">
            <el-icon><House /></el-icon>
          </el-breadcrumb-item>
          <el-breadcrumb-item>查询表格</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <div class="content-area">
        <!-- 筛选卡片：单独分块 -->
        <el-card class="filter-card">
          <template #header>
            <div class="card-header">
              <span>筛选条件</span>
            </div>
          </template>

          <!-- 筛选区域 -->
          <el-form :model="filters" label-width="90px" class="filter-form" label-position="left" inline>
            <el-form-item label="股票代码">
              <el-input v-model="filters.stockCode" placeholder="请输入股票代码" clearable />
            </el-form-item>
            <el-form-item label="股票名称">
              <el-input v-model="filters.stockName" placeholder="请输入股票名称" clearable />
            </el-form-item>
            <el-form-item label="共识状态">
              <el-select v-model="filters.consensus" placeholder="全部" style="width: 160px" clearable>
                <el-option label="全部" value="" />
                <el-option label="多头共识" value="0" />
                <el-option label="多数了结" value="1" />
                <el-option label="新上榜" value="2" />
              </el-select>
            </el-form-item>
         
            <el-form-item label="上榜日期">
              <el-date-picker
                v-model="filters.dateRange"
                type="daterange"
                unlink-panels
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item>
              <el-space>
                <el-button type="primary" @click="onSearch">
                  <el-icon style="margin-right: 4px"><Search /></el-icon>查询
                </el-button>
                <el-button @click="onReset">
                  <el-icon style="margin-right: 4px"><RefreshRight /></el-icon>重置
                </el-button>
              </el-space>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 列表卡片：仅包含表格与分页 -->
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>股票列表</span>
            </div>
          </template>

          <!-- 表格 -->
          <el-table :data="stockList" stripe style="width: 100%">
            <el-table-column prop="stockName" label="股票名称" width="180">
              <template #default="scope">
                <span class="stock-name">{{ scope.row.stockName }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="holderCount" label="游资持有数" width="220">
              <template #default="scope">
                <span>
                  {{ scope.row.holderCount }}
                  <span class="delta" :class="{ up: scope.row.weekDelta > 0, down: scope.row.weekDelta < 0 }">
                    （本周{{ scope.row.weekDelta > 0 ? '新增' : '减少' }}: {{ formatSigned(scope.row.weekDelta) }}）
                  </span>
                </span>
              </template>
            </el-table-column>

            <el-table-column prop="heldAmount" label="持仓总额" width="160">
              <template #default="scope">
                <span>{{ formatAmountWan(scope.row.heldAmount) }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="profitAmount" label="持仓盈亏" width="160">
              <template #default="scope">
                <span :class="{
                  'profit-positive': scope.row.profitAmount > 0,
                  'profit-negative': scope.row.profitAmount < 0
                }">{{ formatAmountWan(scope.row.profitAmount, true) }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="consensusText" label="共识状态" width="140">
              <template #default="scope">
                <span>{{ scope.row.consensusText }}</span>
              </template>
            </el-table-column>

            <el-table-column label="买入/卖出/净金额(近3月)">
              <template #default="scope">
                <TradeProgress
                  :buy-amount="scope.row.buyAmount"
                  :sell-amount="scope.row.sellAmount"
                  :net-buy-amount="scope.row.netBuyAmount"
                  :tooltip="true"
                  :show-labels="true"
                />
              </template>
            </el-table-column>

            <el-table-column label="查看详情" width="120">
              <template #default="scope">
                <el-button link type="primary" size="small" @click="viewHoldings(scope.row)">持仓详情</el-button>
              </template>
            </el-table-column>

            <el-table-column prop="listDate" label="上榜日期" width="140" />
          </el-table>

          <div class="pagination-wrapper">
            <el-pagination
              background
              layout="total, prev, pager, next, jumper"
              :total="pagination.totalCount"
              :page-size="pagination.pageSize"
              :current-page="pagination.pageIndex"
              @current-change="handlePageChange"
            />
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { House, Search, RefreshRight } from '@element-plus/icons-vue'
import TradeProgress from '@/components/TradeProgress.vue'
import { hotMoneyStockAPI } from '@/utils/api'

// 页面状态管理
const pageLoading = ref(false)
const pageError = ref(false)
const errorMessage = ref('')
const errorTitle = ref('请求失败')

// 筛选项
const filters = reactive({
  stockCode: '',
  stockName: '',
  consensus: '', // 对应 HoldState: 0 多头共识, 1 多数了结, 2 新上榜
  strategy: '',
  status: '',
  dateRange: [] // ['YYYY-MM-DD', 'YYYY-MM-DD']
})

// 列表与分页
const stockList = ref([])
const pagination = ref({
  pageIndex: 1,
  pageSize: 20,
  totalCount: 0,
  totalPages: 0,
  hasPrevPages: false,
  hasNextPages: false
})

const formatSigned = (num) => {
  const n = Number(num)
  if (isNaN(n) || n === 0) return '0'
  return n > 0 ? `+${n}` : `${n}`
}

// 金额格式化：转为“万”，保留1位小数，可选显示正负号
const formatAmountWan = (val, withSign = false) => {
  if (val === null || val === undefined || isNaN(Number(val))) return '-'
  const num = Number(val) / 10000
  if (withSign) {
    const sign = num > 0 ? '+' : (num < 0 ? '-' : '')
    const absStr = Math.abs(num).toLocaleString('zh-CN', { minimumFractionDigits: 1, maximumFractionDigits: 1 })
    return `${sign}${absStr}万`
  }
  return `${num.toLocaleString('zh-CN', { minimumFractionDigits: 1, maximumFractionDigits: 1 })}万`
}

// 将后端 holdState 数值转中文
const holdStateText = (val) => {
  const map = { 0: '多头共识', 1: '多数了结', 2: '新上榜' }
  return map?.[val] ?? '-'
}

// 加载数据（接入接口）
const fetchStockList = async () => {
  pageLoading.value = true
  pageError.value = false
  try {
    const payload = {
      StockCode: filters.stockCode?.trim() || undefined,
      StockName: filters.stockName?.trim() || undefined,
      HoldState: filters.consensus === '' ? undefined : Number(filters.consensus),
      StartDate: Array.isArray(filters.dateRange) && filters.dateRange.length === 2 ? filters.dateRange[0] : undefined,
      EndDate: Array.isArray(filters.dateRange) && filters.dateRange.length === 2 ? filters.dateRange[1] : undefined,
      PageIndex: pagination.value.pageIndex,
      PageSize: pagination.value.pageSize
    }

    const res = await hotMoneyStockAPI.getList(payload)

    if (res && res.succeeded && res.data) {
      const data = res.data
      // 映射字段到页面表格结构
      const items = (data.items || []).map(item => ({
        id: item.stockId,
        stockCode: item.stockCode,
        stockName: item.stockName,
        holderCount: item.hotMoneyCount30Day,
        weekDelta: item.hotMoneyCount7DayAdd,
        heldAmount: item.price,
        profitAmount: item.winPrice,
        consensusText: holdStateText(item.holdState),
        buyAmount: item.buyAmount,
        sellAmount: item.sellAmount,
        netBuyAmount: item.netBuyAmount,
        listDate: typeof item.firstBuyData === 'string' ? item.firstBuyData : String(item.firstBuyData)
      }))

      stockList.value = items
      const safePageIndex = data.pageIndex && data.pageIndex > 0 ? data.pageIndex : 1
      const safePageSize = data.pageSize && data.pageSize > 0 ? data.pageSize : pagination.value.pageSize
      pagination.value = {
        pageIndex: safePageIndex,
        pageSize: safePageSize,
        totalCount: (data.totalCount ?? 0),
        totalPages: (data.totalPages ?? 0),
        hasPrevPages: !!data.hasPrevPages,
        hasNextPages: !!data.hasNextPages
      }
      pageLoading.value = false
    } else {
      pageLoading.value = false
      pageError.value = true
      errorTitle.value = '请求失败'
      errorMessage.value = res?.errors || '获取股票列表失败'
    }
  } catch (error) {
    pageLoading.value = false
    pageError.value = true
    errorTitle.value = '请求失败'
    errorMessage.value = error?.message || '获取股票列表失败'
  }
}

// 交互
const onSearch = () => {
  pagination.value.pageIndex = 1
  fetchStockList()
}

const onReset = () => {
  filters.stockCode = ''
  filters.stockName = ''
  filters.consensus = ''
  filters.strategy = ''
  filters.status = ''
  filters.dateRange = []
  pagination.value.pageIndex = 1
  fetchStockList()
}

const handlePageChange = (page) => {
  pagination.value.pageIndex = page
  fetchStockList()
}

const viewHoldings = (row) => {
  ElMessage.info(`即将查看【${row.stockName}】的持仓详情（示例）`)
}

const retryLoad = () => fetchStockList()

onMounted(() => {
  fetchStockList()
})
</script>

<style scoped>
.card-header {
  font-family: HarmonyOS Sans SC;
  font-size: 16px;
  font-weight: 500;
  line-height: 24px;
  display: flex;
  align-items: center;
  letter-spacing: normal;
  color: #1d2129;
}

.stock-list {
  padding: 24px;
}

/* 页面级Loading样式 */
.page-loading {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
}

.loading-overlay {
  width: 100%;
  height: 100%;
}

/* 错误页面样式 */
.page-error {
  padding: 40px 20px;
}

.page-header {
  margin-bottom: 24px;
}

.content-area {
  display: grid;
  gap: 16px;
  min-height: 400px;
}

.filter-form {
  /* 单独卡片后无需底部外边距 */
  margin-bottom: 0;
}

.stock-name {
  font-weight: 500;
  color: #303133;
}

.delta {
  margin-left: 6px;
}

.up {
  color: #ea0000;
}

.down {
  color: #529b2e;
}

.profit-positive {
  color: #ea0000;
  font-weight: 600;
}

.profit-negative {
  color: #529b2e;
  font-weight: 600;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

:deep(.el-table) {
  font-family: 'Inter', 'HarmonyOS Sans SC', sans-serif;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #909399;
  font-weight: 600;
  font-size: 14px;
}

:deep(.el-table td) {
  font-size: 14px;
  color: #303133;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #f5f7fa;
}
</style>